package org.swingDemo.swingWorker;

import cn.hutool.core.util.RandomUtil;

import javax.swing.*;
import java.util.*;

public class GeneratorWorker extends SwingWorker<Void, Void> {

    private int count;
    private int ticketType;

    private static final int Red_Count = 6; // 红球个数
    private static final int Red_Max_Number = 33;   // 红球的最大号码
    private static final int Blue_Count = 1;    // 蓝球个数
    private static final int Blue_Max_Number = 16;  // 蓝球的最大号码

    public GeneratorWorker(int count, int ticketType) {
        this.count = count;
        this.ticketType = ticketType;
    }

    @Override
    protected Void doInBackground() throws Exception {
        List<Integer> redBalls = new ArrayList<>();
        for (int i = 0; i < Red_Max_Number; i++) {
            redBalls.add(i + 1);
        }
        List<Integer> blueBalls = new ArrayList<>();
        for (int i = 0; i < Blue_Max_Number; i++) {
            blueBalls.add(i + 1);
        }
        // 获取红球
        for (int i = 0; i < Red_Count; ++i) {
            Integer mostNumber = getMostCountNumber(redBalls);
            firePropertyChange("result", -1, mostNumber);
            redBalls.remove(mostNumber);
        }

        // 获取蓝球
        for (int i = 0; i < Blue_Count; ++i) {
            Integer mostNumber = getMostCountNumber(blueBalls);
            firePropertyChange("result", -1, mostNumber);
            redBalls.remove(mostNumber);
        }
        return null;
    }

    // 获取随机取到次数最多的数字
    private Integer getMostCountNumber(List<Integer> balls) {
        Map<Integer, Integer> numberMap = new HashMap<>();
        for (int j = 0; j < count; j++) {
            Integer number = RandomUtil.randomEle(balls);
            if (!numberMap.containsKey(number)) {
                numberMap.put(number, 1);
            } else {
                numberMap.put(number, numberMap.get(number) + 1);
            }
        }

        System.out.println(numberMap);
        Integer mostNumber = null, mostNumberCount = 0;
        Set<Map.Entry<Integer, Integer>> entries = numberMap.entrySet();
        for (Map.Entry<Integer, Integer> entry : entries) {
            if (mostNumberCount < entry.getValue()) {
                mostNumber = entry.getKey();
                mostNumberCount = entry.getValue();
            }
        }
        return mostNumber;
    }

    @Override
    protected void done() {
        super.done();
    }
}
